<?php
/**
 * Created by PhpStorm.
 * Author: huangwy
 * Date: 2018/3/15 16:16
 * Version: 1.0
 */
namespace app\admin\controller;

use think\Db;
use think\facade\Request;

class Variable extends Base{
    public function index()
    {
        $prefix = config('database.prefix');
        $vars = Db::query('select * from '.$prefix.'setting where type=1');
        $this->assign('vars', $vars);
        return view();
    }

    public function add()
    {
        $var = array('k'=>'','name'=>'','v'=>'');
        $this->assign('var', $var);
        return view('form');
    }

    public function edit($k)
    {
        $prefix = config('database.prefix');
        $sql = Db::query('select * from '.$prefix.'setting where k="'.$k.'" limit 1');
        $var = $sql[0];
        if (!$var) {
            $this->error('参数错误！');
        }

        $this->assign('var', $var);
        return view('form');
    }

    public function del()
    {
        $prefix = config('database.prefix');
        $k = input('k');
        if ($k <> '') {
            if (db('setting')->where("type=1 and k='{$k}'")->delete()) {
                addlog('删除自定义变量，ID：' . $k);
                return json(['flag'=>0,'message'=>'恭喜，删除成功！']);
            } else {
                return json(['flag'=>1,'message'=>',删除失败！']);
            }
        } else {
            return json(['flag'=>1,'message'=>'参数错误！']);
        }
    }

    public function update()
    {

        $data['k'] = input('k');
        $varname = input('post.varname');
        $prefix = config('database.prefix');
        if ($data['k'] == '') {
            return json(['flag'=>1,'message'=>'变量名不能为空！']);
        }
        if (Db::query('select * from '.$prefix.'setting where k="'.$data['k'].'" limit 1') && $varname == '') {
            return json(['flag'=>1,'message'=>'变量名称已经存在！']);
        }
        $data['v'] = input('post.v');
        $data['name'] = input('post.name');
        $data['type'] = 1;//自定义
        if ($varname == '') {
//            dump("insert into {$prefix}setting (k,v, name, type) values ('{$data[k]}','{$data[v]}','{$data[name]}','{$data[type]}')");die;
            DB::query("insert into {$prefix}setting (k,v, name, type) values ('{$data[k]}','{$data[v]}','{$data[name]}','{$data[type]}')");
            addlog('新增自定义变量：' . $data['k']);
        } else {
            DB::query('update '.$prefix.'setting set v="'.$data['v'].'", name="'.$data['name'].'", type="'.$data['type'].'" where k="'.$data['k'].'"');
            addlog('新增自定义变量：' . $data['k']);
        }

        return json(['flag'=>0,'message'=>'恭喜，操作成功！']);
    }
}